package com.mriassl.rabbitmq.unbind;

import java.io.IOException;
import java.text.MessageFormat;

import com.mriassl.rabbitmq.base.AbstractConsumer;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

public class UnbindHandler02 extends AbstractConsumer{

	
	@Override
	protected void handle() throws Exception {
		channel.exchangeDeclare(Consts.EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
		channel.queueDeclare(Consts.QUEUE_NAME, false, false, false, null);
		channel.queueBind(Consts.QUEUE_NAME, Consts.EXCHANGE_NAME, Consts.ROUTING_KEY);

		System.out.println(" UnackHandler01 Waiting for messages. To exit press CTRL+C");

		Consumer consumer = new DefaultConsumer(channel) {
			@Override
			public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body) throws IOException {
				long deliveryTag = envelope.getDeliveryTag();
				if(consume(deliveryTag)) {
				    String message = new String(body, "UTF-8");
				    System.out.println(MessageFormat.format("UnbindHandler01 Received RoutingKey:{0},DeliveryTag:{1},Message:{2}", envelope.getRoutingKey(),envelope.getDeliveryTag(),message));
				    getChannel().setDefaultConsumer(null);
				    getChannel().basicAck(deliveryTag, true);
				}else {
                    getChannel().basicNack(deliveryTag, false, true);
                }
			}
		};
		channel.basicQos(1);
		channel.basicConsume(Consts.QUEUE_NAME, false, consumer);
	}
	
	private boolean consume(long deliveryTag) {
	    return deliveryTag%9==1;
	}
	
}
